package com.alan.cueencoding.util;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.SortedMap;

/**
 * @author Alan.Xiao
 * @date 2022/10/4
 */
@Slf4j
public class FileEncodeUtil {

    public static List<MatchingResult> findMatchingFileEncodings(byte[] bytes, List<String> matchPattern) {
        SortedMap<String, Charset> charsetsToFind = Charset.availableCharsets();
        List<MatchingResult> matchingResults = new ArrayList<>(charsetsToFind.size() / 2);

        charsetsToFind.forEach((name, charset) -> {
            String contentToMatch = new String(bytes, charset);
            Optional<String> matched = matchPattern.parallelStream()
                    .map(pattern -> patternPreProcess(pattern))
                    .filter(contentToMatch::contains).findAny();

            if (matched.isPresent()) {
                MatchingResult matchingResult = buildMatchingResult(contentToMatch, name, charset);
                matchingResults.add(matchingResult);
            }

            log.info("【{}】 - 【{}】", name, contentToMatch);
        });

        return matchingResults;
    }

    private static MatchingResult buildMatchingResult(String contentToMatch, String charsetName, Charset charset) {
        return MatchingResult.builder()
                .charset(charset)
                .decodedContent(contentToMatch)
                .charsetName(charsetName)
                .build();
    }

    private static String patternPreProcess(String pattern) {
        return pattern;
    }
}
